#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Time          : 2024/4/29 16:04
# File          : log_out.py
# @Author       : MingTai
# @Department   : automation_qa
# python log封装
import logging
from logging.handlers import RotatingFileHandler


# 封装的日志管理类
class LogManager:

    def __init__(self, log_name='app.log', log_level=logging.INFO,
                 log_format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'):
        # 创建一个logger对象
        self.logger = logging.getLogger(log_name)
        self.logger.setLevel(log_level)

        # 设置日志格式
        formatter = logging.Formatter(log_format)

        # 创建一个handler，用于写入日志文件
        file_handler = RotatingFileHandler(log_name, maxBytes=1024 * 1024 * 5, backupCount=5)
        file_handler.setLevel(log_level)
        file_handler.setFormatter(formatter)

        # 创建一个handler，用于输出到控制台
        console_handler = logging.StreamHandler()
        console_handler.setLevel(log_level)
        console_handler.setFormatter(formatter)

        # 给logger添加handler
        self.logger.addHandler(file_handler)
        self.logger.addHandler(console_handler)

        # 防止日志输出重复问题
        self.logger.propagate = False

    def get_logger(self):
        """
        获取Logger对象的实例，以便外部调用。
        """
        return self.logger


# 使用单例模式保证全局使用同一个logger实例
logger_instance = LogManager().get_logger()


# 供外部调用的日志记录方法
def debug(message):
    logger_instance.debug(message)


def info(message):
    logger_instance.info(message)


def warning(message):
    logger_instance.warning(message)


def error(message):
    logger_instance.error(message)


def critical(message):
    logger_instance.critical(message)


if __name__ == '__main__':
    # 测试日志功能
    debug('This is a debug message')
    info('This is an info message')
    warning('This is a warning message')
    error('This is an error message')
    critical('This is a critical message')
